package com.studyroom.service.oss.impl;

import com.studyroom.mapper.BasicImageMapper;
import com.studyroom.pojo.BasicImage;
import com.studyroom.service.oss.OssService;
import com.studyroom.util.OSSClientUtils;
import com.studyroom.vo.admin.OssResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.time.LocalDateTime;

/**
 * @author wuhongbin
 * @createTime 2022年03月13日 16:09:00
 */
@Service
public class OssServiceImpl implements OssService {

    private final BasicImageMapper basicImageMapper;

    @Value("${image.url}")
    private String imageUrl;

    @Autowired
    public OssServiceImpl(BasicImageMapper basicImageMapper){
        this.basicImageMapper = basicImageMapper;
    }

    @Override
    public OssResultVo uploadImage(MultipartFile imageFile) {
        BufferedImage imageBuffered=null;
        try {
            imageBuffered = ImageIO.read(imageFile.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }

        String image = OSSClientUtils.uploadFileNew(imageFile, "new_"+imageFile.getOriginalFilename(), "image");
        Integer imageId = uploadImage(image, imageBuffered);

        OssResultVo ossResultVo = new OssResultVo();
        ossResultVo.setImageId(imageId);
        ossResultVo.setImageName(image);
        ossResultVo.setImageUrl(imageUrl + image);
        return ossResultVo;
    }

    /**
     * 上传图片到数据库
     * @param image         图片
     * @param imageBuffered 读取
     * @return 数据库图片ID
     */
    private Integer uploadImage(String image, BufferedImage imageBuffered) {
        int width;
        int height;
        try {
            width = imageBuffered.getWidth();
            height = imageBuffered.getHeight();
        } catch (Exception e) {
            return null;
        }
        BasicImage basicImage = new BasicImage();
        basicImage.setBucket(0);
        basicImage.setFileName(image);
        basicImage.setHeight(height);
        basicImage.setWidth(width);
        basicImage.setIsGif(0);
        basicImageMapper.insertReturnId(basicImage);
        return basicImage.getId();
    }
}
